//
//  HZJPictureView.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/13.
//  Copyright © 2015年 hzj. All rights reserved.
//

import UIKit
import SDWebImage

let HZJPICTURECELLID = "HZJPICTURECELLID"

class HZJPictureView: UICollectionView {
    /// 模型
    var statusesViewModel:StatusesViewModel?{
        didSet{
            
            sizeToFit()
            
            reloadData()
        }
    }
    //调用sizeToFit（）时会调用此法
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calculateTheSize()
        
//        return calcViewSize()
    }
    
    
    /// 根据模型中的图片数量来计算视图大小
    private func calcViewSize() -> CGSize {
        // 1. 准备工作
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        // 设置默认大小
        layout.itemSize = CGSize(width: HZJPICTUREWIDTH, height: HZJPICTUREWIDTH)
        
        // 2. 根据图片数量来计算大小
        let count = statusesViewModel?.thumbnailURLs!.count ?? 0

        
        // 1> 没有图
        if count == 0 {
            return CGSizeZero
        }
        
        // 2> 1张图
        if count == 1 {
            // TODO: - 临时返回一个大小
            let size = CGSize(width: 150, height: 150)
            
            layout.itemSize = size
            return size
        }
        
        // 3> 4张图 2 * 2
        if count == 4 {
            let w = 2 * HZJPICTUREWIDTH + HZJPICTUREMARGIN
            
            return CGSize(width: w, height: w)
        }
        
        // 4> 其他
        /**
        2, 3,
        5, 6,
        7, 8, 9
        */
        // 计算显示图片的行数
        let row = CGFloat((count - 1) / 3 + 1)
        let h = row * HZJPICTUREWIDTH + (row - 1) * HZJPICTUREMARGIN
        let w = 2 * (HZJPICTUREWIDTH + HZJPICTUREMARGIN)
        
        return CGSize(width: w, height: h)
    }
    
    /// 计算附加图片框的高度
    private  func calculateTheSize()->CGSize{
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(HZJPICTUREWIDTH, HZJPICTUREHEIGHT)
        
        let count = statusesViewModel?.thumbnailURLs!.count ?? 0
        var w:CGFloat
        var h:CGFloat
        if count == 0{
            w = 0
            h = 0
            return CGSizeMake(w, h)
        }
        if count == 1 {
            
            var size  = CGSizeMake(HZJPICTURESIZE, HZJPICTURESIZE)
            
            let key = statusesViewModel?.thumbnailURLs![0].absoluteString
            
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key){
                size = image.size
            }
            
            //确保图片宽度在40~300之间
            size.width = size.width < 40 ? 40 :size.width
            size.width = size.width > 300 ? 300 :size.width
            
            layout.itemSize = size
            return size
        }
        if count == 4{
            w = 2 * HZJPICTUREWIDTH + HZJPICTUREMARGIN
            h = 2 * HZJPICTUREWIDTH + HZJPICTUREMARGIN
            return  CGSizeMake(w, h)
        }
        let row = CGFloat((count - 1) / 3 + 1)
        w = HZJPICTURESIZE
        h = row * (HZJPICTUREWIDTH + HZJPICTUREMARGIN) - HZJPICTUREMARGIN
        return CGSizeMake(w, h)
        
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        //背景色
        backgroundColor = UIColor.whiteColor()

        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.minimumInteritemSpacing = HZJPICTUREMARGIN
        layout.minimumLineSpacing = HZJPICTUREMARGIN
//        layout.itemSize = CGSizeMake(HZJPICTUREWIDH, HZJPICTUREHEIGHT)
        
        dataSource = self
        
        //注册cell
        registerClass(HZJPictureViewcell.self, forCellWithReuseIdentifier: HZJPICTURECELLID)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

}
extension HZJPictureView:UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return statusesViewModel?.thumbnailURLs?.count ?? 0
        
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HZJPICTURECELLID, forIndexPath: indexPath) as! HZJPictureViewcell
        cell.imageURL = statusesViewModel!.thumbnailURLs![indexPath.item]
        return cell
    }
}
/// 自定义cell

class HZJPictureViewcell:UICollectionViewCell {
    /// 配图视图的 URL
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.whiteColor()
        addSubview(iconView)
        
        
        
        
        //MARK:- 此处必须设置上下左右的约束，设置宽高没用
        iconView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))

        //利用老师的框架
//        iconView.ff_Fill(self)

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 懒加载
    private let iconView: UIImageView = {
        let iv = UIImageView()
        //设定图片填充模式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()

    
}


